/* eslint-disable @typescript-eslint/no-explicit-any */
import * as mqtt from 'mqtt/dist/mqtt.min'
import { useGasStore } from '@/store'

import emitter from '@/utils/eventBus'
// import emitter from './emitter'

let mqttUrl = ''
const gasStore: any = useGasStore()
const isDev = process.env.NODE_ENV === 'development'
if (isDev) {
  mqttUrl = 'ws://192.168.1.101:8083/mqtt'
} else {
  mqttUrl = window.location.origin + '/mqtt'
  // mqttUrl = 'ws://192.168.10.103:1888/mqtt'
}
// console.log(mqttUrl)
function S4 () {
  return (((1 + Math.random()) * 0x10000) | 0).toString(32).substring(1)
}
const MathRandom = (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())

const options = {
  username: 'admin',
  password: '1qaz@WSX',
  clean: true, // true: 清除会话, false: 保留会话
  connectTimeout: 4000, // 超时时间
  clientId: 'clientid-' + MathRandom
}
// const topics = ['co', 'ch4', 'smoke', 'o2', 'fog', 'openfirecoal', 'coalstatus']
const topics = [ 'devices/+/telemetry' ]
let client: any = null
export function mqttStart () {
  console.log('mqttWeb连接--------------->' )
  console.log(mqttUrl, options)
  client = mqtt.connect(mqttUrl, options)
  // const client = mqtt.connect(, options)
  client.on('connect', (e: {}) => {
    console.log('mqttWeb连接成功--------------->', e)
    gasStore.saveCOData('aaa')
  })
  // 断开发起重连
  client.on('reconnect', (message:any) => {
    
    console.log('mqttWeb正在重连...', message)
  })
  // 链接异常处理
  client.on('error', (error: {}) => {
    console.log('mqttWeb连接失败...', error)
  })
  topics.forEach(topic => {
    console.log('循环topic--------------->', topic)
    client.subscribe(topic)
  })
  // client.subscribe('warn') 
  client.on('message', (topic: string, message: any) => {
    // console.log('获取的message--------------->', JSON.parse(message), message)
    try {
      const msg = JSON.parse(message)
      emitter.emit('updateData', msg)
      // switch (topic) {
      // case 'co':
      //   emitter.emit('COData', msg)
      //   break
      // case 'ch4':
      //   emitter.emit('CH4Data', msg)
      //   break
      // case 'smoke':
      //   emitter.emit('SmokeData', msg)
      //   break
      // case 'o2':
      //   emitter.emit('O2Data', msg)
      //   break
      // case 'fog':
      //   emitter.emit('DustData', msg)
      //   break
      // case 'openfirecoal':
      //   emitter.emit('FlameCoalData', msg)
      //   break
      // case 'coalstatus':
      //   emitter.emit('LinkStatusData', msg)
      //   break
      // }
      if (topics.includes(topic)) {
        // emitter.emit(topic, msg)
      }
    } catch (error) {
      console.log(error)
    }
  })
}
export function mqttStop () {
  if (client && client.connected) {
    try {
      client.end(false, () => {
        console.log('mqtt断开成功')
      })
    } catch (error) {
      console.log('mqtt断开失败', error)
    }
  }
}
// mqttStart()
